/**
 * 联动选择 年月日
 * @param {Object} [config = {}]
 *        config.selected = new Date()               // 默认选择的日期（日期类型）
 *               selected = "2021-2-26"              // 默认选择的日期（字符串类型）
 *               selected = 1614268800000            // 默认选择的日期（时间戳类型）
 *               selected = null                     // 默认选择的日期（空显示待选状态）
 *               selected = {                        // 默认选择的日期（对象标识）
 *                   year : 2021 || 0,               // 为空时待选
 *                   month : 2 || 0,                 // 为空时待选
 *                   day : 26 || 0,                  // 为空时待选
 *               }
 *        config.advanceYear = 0                     // 往当然年继续生成几年
 *        config.delayYear = 0                       // 往当然年倒回生成几年
 *        config.yearSelector = "#year"              // 年选择器
 *        config.monthSelector = "#month"            // 月选择器
 *        config.daySelector = "#day"                // 日选择器
 *        config.onInstalled = function(this){}      // 初始化完成事件
 *        config.onChangeYear = function(this){}     // 年改变事件
 *        config.onChangeMonth = function(this){}    // 月改变事件
 *        config.onChangeDay = function(this){}      // 日改变事件
 *        config.onChange = function(this,event){}   // 改变事件
 *
 *        this.year = 2021 || 0                      // 当前年（待选择时为0）
 *        this.yearMax = 2021                        // 选择最大年
 *        this.yearMin = 2021                        // 选择最小年
 *        this.month = 2 || 0                        // 当前月（待选择时为0）
 *        this.day = 26 || 0                         // 当前日（待选择时为0）
 * @constructor
 */
function CascadeDate(config) {
    var _this = this;
    var _date = new Date();

    //参数初始化
    if (typeof config != "object") {
        config = {};
    }
    if (typeof config.selected == "string"
        || typeof config.selected == "number") {
        _date = new Date(config.selected);
    } else if (config.selected instanceof Date) {
        _date = config.selected;
    } else if (config.selected === null) {
    } else if (typeof config.selected == "object") {
        if (!config.selected.year
            && !config.selected.month
            && !config.selected.day) {
            config.selected = null;
        } else {
            if (!config.selected.year) {
                config.selected.year = 0;
            }
            if (!config.selected.month) {
                config.selected.month = 0;
            }
            if (!config.selected.day) {
                config.selected.day = 0;
            }
        }
    }
    if (config.advanceYear == undefined) {
        config.advanceYear = 0;
    }
    if (config.delayYear == undefined) {
        config.delayYear = 0;
    }
    if (typeof config.yearSelector != "string") {
        config.yearSelector = "#year";
    }
    if (typeof config.monthSelector != "string") {
        config.monthSelector = "#month";
    }
    if (typeof config.daySelector != "string") {
        config.daySelector = "#day";
    }
    if (typeof config.onInstalled != "function") {
        config.onInstalled = function () {
        };
    }
    if (typeof config.onChangeYear != "function") {
        config.onChangeYear = function () {
        };
    }
    if (typeof config.onChangeMonth != "function") {
        config.onChangeMonth = function () {
        };
    }
    if (typeof config.onChangeDay != "function") {
        config.onChangeDay = function () {
        };
    }
    if (typeof config.onChange != "function") {
        config.onChange = function () {
        };
    }

    //年月日
    this.year = initYearMonthDay("year");
    this.yearMax = initYearMonthDay("yearMax");
    this.yearMin = initYearMonthDay("yearMin");
    this.month = initYearMonthDay("month");
    this.day = initYearMonthDay("day");
    _date = undefined;

    function initYearMonthDay(type) {
        switch (type) {
            case "year":
                if (config.selected !== null) {
                    return typeof config.selected == "object"
                        ? config.selected.year
                        : _date.getFullYear();
                } else {
                    return 0;
                }
            case "yearMax":
                return _date.getFullYear() + config.advanceYear;
            case "yearMin":
                return _date.getFullYear() - config.delayYear;
            case "month":
                if (config.selected !== null) {
                    return typeof config.selected == "object"
                        ? config.selected.month
                        : _date.getMonth() + 1;
                } else {
                    return 0;
                }
            case "day":
                if (config.selected !== null) {
                    return typeof config.selected == "object"
                        ? config.selected.day
                        : _date.getDate();
                } else {
                    return 0;
                }
        }
        return 0;
    }

    //渲染年月日
    renderYear();
    renderMonth();
    renderDay();

    //年月日事件
    $(config.yearSelector).change(function () {
        _this.year = $(this).val() * 1;
        if (_this.year == 0) {
            _this.month = 0;
            _this.day = 0;
        }
        renderMonth();
        renderDay();
        config.onChangeYear(_this);
        config.onChange(_this, "onChangeYear");
    });

    $(config.monthSelector).change(function () {
        _this.month = $(this).val() * 1;
        if (_this.month == 0) {
            _this.day = 0;
        }
        renderDay();
        config.onChangeMonth(_this);
        config.onChange(_this, "onChangeMonth");
    });

    $(config.daySelector).change(function () {
        _this.day = $(this).val() * 1;
        config.onChangeDay(_this);
        config.onChange(_this, "onChangeDay");
    });

    //初始化完成事件
    config.onInstalled(_this);

    function renderYear() {
        $(config.yearSelector).html((function () {
            var list = ['<option value="0">选择年</option>'];
            for (var cur = _this.yearMax, max = _this.yearMax, min = _this.yearMin;
                 cur >= min;
                 cur--) {
                if (cur == _this.year) {
                    list.push('<option value="' + cur + '" selected>' + cur + '年</option>')
                } else {
                    list.push('<option value="' + cur + '">' + cur + '年</option>')
                }
            }
            return list.join("");
        })());
    }

    function renderMonth() {
        $(config.monthSelector).html((function () {
            var list = ['<option value="0">选择月</option>'];
            for (var i = 1, len = 12; i <= len; i++) {
                if (i == _this.month) {
                    list.push('<option value="' + i + '" selected>' + i + '月</option>')
                } else {
                    list.push('<option value="' + i + '">' + i + '月</option>')
                }
            }
            return list.join("");
        })());
    }

    function renderDay() {
        $(config.daySelector).html((function () {
            var date = new Date(_this.year + '-' + _this.month + '-1');
            var nextDate = new Date((new Date(date.getTime() + 24 * 60 * 60 * 31 * 1000)).getTime());
            var maxDay = ((new Date(nextDate.getFullYear() + '-' + (nextDate.getMonth() + 1) + '-1')).getTime() - date.getTime()) / (24 * 60 * 60 * 1000);

            var list = ['<option value="0">选择日</option>'];
            for (var i = 1, len = maxDay; i <= len; i++) {
                if (i == _this.day) {
                    list.push('<option value="' + i + '" selected>' + i + '日</option>')
                } else {
                    list.push('<option value="' + i + '">' + i + '日</option>')
                }
            }
            return list.join("");
        })());
    }
}
